package com.ningju.procurement.core.questionnaire.service;

import com.ningju.procurement.common.mybatis.pager.PageContext;
import com.ningju.procurement.common.service.BaseServiceImpl;
import com.ningju.procurement.core.questionnaire.bean.Dimension;
import com.ningju.procurement.core.questionnaire.bean.Project;
import com.ningju.procurement.core.questionnaire.bean.Topic;
import com.ningju.procurement.core.questionnaire.dao.TopicDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 源题目管理
 */
@Service
public class TopicService extends BaseServiceImpl<TopicDao, Topic> {

    @Autowired
    private TopicDao topicDao;

    @Autowired
    private AnswerService answerService;

    /**
     * 获得项目的题目列表
     * @param project
     * @return
     */
    public List<Topic> getTopicListByProject(Project project) {

        Assert.notNull(project);

        return topicDao.selectTopicListByProject(project, PageContext.getPage());
    }

    /**
     * 获得未绑定纬度解释的题目列表
     * @return
     */
    public List<Topic> getUnBindDimensionTopicList() {
        return topicDao.selectUnBindDimensionTopicList();
    }

    /**
     * 绑定纬度解释到题目
     * @return
     */
    @Transactional
    public boolean bindDimensionToTopic(Dimension dimension, Topic topic) {

        Assert.notNull(dimension);
        Assert.notNull(topic);

        topic.setDimension(dimension);
        topic.setDimensionId(dimension.getId());

        return save(topic);
    }

    /**
     * 批量绑定试题到纬度解释
     * @param dimension
     * @param topicList
     * @return
     */
    @Transactional
    public boolean bindDimensionToTopicList(Dimension dimension, List<Topic> topicList) {
        Assert.notNull(dimension);
        Assert.notEmpty(topicList);

        topicList.forEach((topic) -> {
            bindDimensionToTopic(dimension, topic);
        });

        return true;
    }

    @Transactional
    public boolean save(Topic topic) {

        topic.getAnswerList().forEach((answer) -> {
            answer.setTopicId(topic.getId());
            answerService.save(answer);
        });

        return super.save(topicDao, topic);
    }

    @Transactional
    public boolean destory(Topic topic) {
        if(answerService.destoryByTopic(topic)) {
            return topicDao.deleteById(topic.getId()) > 0;
        }
        return false;
    }

    @Transactional
    public boolean destory(List<Long> topicIds) {

        topicIds.parallelStream().forEach((id) -> {
            Topic topic = new Topic();
            topic.setId(id);
            answerService.destoryByTopic(topic);
        });

        return super.deleteByIds(topicDao, topicIds);
    }

}